<template>
    <div class="app-container">
      <!-- 标题栏 -->
      <div class="title-bar" @mousedown="startDrag">
        <div class="title-content">
          <img src="@/assets/keaiicon.png" class="title-icon">
          <h1 class="title-text">超级打印姬</h1>
        </div>
        <div class="title-buttons">
          <button class="title-button" @click="minimize">－</button>
          <button class="title-button" @click="toggleMaximize">
            {{ isMaximized ? '🗗' : '🗖' }}
          </button>
          <button class="title-button close" @click="close">×</button>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="main-content">
        <div class="left-panel">
          <!-- 打印机选择 -->
          <div class="printer-card">
            <img src="@/assets/keaiicon.png" class="printer-icon">
            <select v-model="selectedPrinter" class="printer-select">
              <option v-for="printer in printers" :key="printer.name" :value="printer.name">
                {{ printer.name }}{{ printer.isDefault ? ' (默认)' : '' }}
              </option>
            </select>
            <button class="refresh-button" @click="refreshPrinters">
              <span class="icon">🔄</span>
            </button>
          </div>

          <!-- 搜索框 -->
          <div class="search-card">
            <input
              v-model="searchTerm"
              class="search-input"
              placeholder="🔍 搜索文件..."
            />
            <button class="clear-button" @click="clearSearch" v-if="searchTerm">×</button>
          </div>

          <!-- 文件列表 -->
          <div class="list-card">
            <div class="file-list-header">
              <span>文件名</span>
              <span>操作</span>
            </div>
            <div class="file-list-container">
              <div
                v-for="(file, index) in filteredFiles"
                :key="index"
                class="file-item"
                :class="{ selected: selectedFiles.includes(file) }"
                @click="toggleSelect(file)"
              >
                <span class="file-name">{{ getFileName(file) }}</span>
                <div class="file-actions">
                  <button @click.stop="showInFolder(file)" title="在文件夹中显示">📂</button>
                  <button @click.stop="removeFile(file)" title="移除">🗑️</button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧操作区 -->
        <div class="right-panel">
          <button class="action-button" @click="addFiles">
            <span class="icon">📁</span> 添加文件
          </button>
          <button
            class="action-button"
            @click="removeSelected"
            :disabled="selectedFiles.length === 0"
          >
            <span class="icon">🗑️</span> 移除选中
          </button>
          <button
            class="action-button"
            @click="clearList"
            :disabled="files.length === 0"
          >
            <span class="icon">🧹</span> 清空列表
          </button>

          <!-- 打印设置 -->
          <div class="print-settings">
            <label>
              <input type="checkbox" v-model="duplexPrinting" /> 双面打印
            </label>
            <label>
              <input type="number" v-model.number="copies" min="1" class="copies-input" /> 份数
            </label>
          </div>

          <div class="spacer"></div>

          <button
            class="print-button"
            @click="startPrinting"
            :disabled="files.length === 0 || !selectedPrinter"
          >
            <span class="icon">🖨️</span> 开始打印 ({{ files.length }})
          </button>
        </div>
      </div>

      <!-- 状态栏 -->
      <div class="status-bar">
        <div class="status-info">
          <span>{{ statusMessage }}</span>
          <span v-if="printingProgress > 0">
            正在打印 {{ printingProgress }}/{{ files.length }}
          </span>
        </div>
        <div class="progress-container">
          <div class="progress-bar" :style="{ width: `${progress}%` }"></div>
        </div>
      </div>

      <!-- 通知 -->
      <transition name="notification">
        <div
          v-if="notification.show"
          class="notification"
          :class="notification.type"
        >
          {{ notification.message }}
        </div>
      </transition>
    </div>
  </template>

  <script>
  export default {
    data() {
      return {
        files: [],
        selectedFiles: [],
        searchTerm: '',
        printers: [],
        selectedPrinter: '',
        statusMessage: '准备好打印文件啦~',
        progress: 0,
        printingProgress: 0,
        isMaximized: false,
        notification: {
          show: false,
          message: '',
          type: 'info' // 'info' 或 'error'
        },
        duplexPrinting: false,
        copies: 1
      }
    },
    computed: {
      filteredFiles() {
        const term = this.searchTerm.toLowerCase()
        return this.files.filter(file =>
          this.getFileName(file).toLowerCase().includes(term)
        )
      }
    },
    async mounted() {
      await this.refreshPrinters()
      this.setupWindowListeners()
    },
    methods: {
      // 窗口控制方法
      setupWindowListeners() {
        if (window.electronAPI.platform === 'win32') {
          window.addEventListener('resize', this.checkMaximized)
        }
      },
      checkMaximized() {
        // 简单根据窗口宽度判断是否最大化，仅供参考
        this.isMaximized = window.outerWidth >= screen.availWidth
      },
      minimize() {
        window.electronAPI.minimizeWindow()
      },
      toggleMaximize() {
        window.electronAPI.maximizeWindow()
        this.isMaximized = !this.isMaximized
      },
      close() {
        window.electronAPI.closeWindow()
      },
      startDrag() {
        // 调用预加载中暴露的 startDrag（如果你在主进程对此提供了处理）
        window.electronAPI.startDrag && window.electronAPI.startDrag()
      },

      // 文件操作方法
      getFileName(path) {
        return path.split(/[\\/]/).pop()
      },
      async addFiles() {
        try {
          // openFileDialog 不需要传递参数时可直接调用
          const files = await window.electronAPI.openFileDialog()
          if (files && files.length) {
            // 通过 Set 去重
            this.files = [...new Set([...this.files, ...files])]
            this.showNotification(`添加了 ${files.length} 个文件`, 'info')
            this.statusMessage = `已加载 ${this.files.length} 个文件`
          }
        } catch (error) {
          this.showNotification('添加文件失败: ' + error.message, 'error')
        }
      },
      toggleSelect(file) {
        const index = this.selectedFiles.indexOf(file)
        if (index === -1) {
          this.selectedFiles.push(file)
        } else {
          this.selectedFiles.splice(index, 1)
        }
      },
      removeFile(file) {
        this.files = this.files.filter(f => f !== file)
        this.selectedFiles = this.selectedFiles.filter(f => f !== file)
      },
      removeSelected() {
        if (this.selectedFiles.length === 0) return
        this.files = this.files.filter(file => !this.selectedFiles.includes(file))
        this.selectedFiles = []
      },
      clearList() {
        if (this.files.length === 0) return
        this.files = []
        this.selectedFiles = []
        this.statusMessage = '列表已清空'
      },
      // 在文件夹中显示
  async showInFolder(filePath) {
    try {
      const result = await window.electronAPI.showItemInFolder(filePath)
      if (!result.success) {
        throw new Error(result.error || '未知错误')
      }
    } catch (error) {
      this.showNotification(`无法打开文件夹: ${error.message}`, 'error')
    }
  },
      clearSearch() {
        this.searchTerm = ''
      },

      // 打印机功能方法
      async refreshPrinters() {
        try {
          this.printers = await window.electronAPI.getPrinters()
          const defaultPrinter = this.printers.find(p => p.isDefault)
          this.selectedPrinter = defaultPrinter ? defaultPrinter.name : ''
          this.statusMessage = this.printers.length
            ? '打印机列表已更新'
            : '未检测到打印机'
        } catch (error) {
          this.showNotification('获取打印机失败: ' + error.message, 'error')
        }
      },

      // 打印文件
  async printFile(filePath) {
    if (!this.selectedPrinter) return

    try {
      const result = await window.electronAPI.printFile({
        filePath,
        printerName: this.selectedPrinter
      })

      if (!result.success) {
        throw new Error(result.error)
      }
      return true
    } catch (error) {
      this.showNotification(`打印失败: ${error.message}`, 'error')
      return false
    }
  },

      // 打印功能方法
      async startPrinting() {
        if (!this.selectedPrinter || this.files.length === 0) return

        try {
          this.progress = 0
          this.printingProgress = 0
          this.statusMessage = '开始打印...'

          for (let i = 0; i < this.files.length; i++) {
            const file = this.files[i]
            this.printingProgress = i + 1
            this.statusMessage = `正在打印 ${i + 1}/${this.files.length}: ${this.getFileName(file)}`

            // 打印参数中传递文件路径、打印机名称、是否双面打印和份数
            const result = await window.electronAPI.printFile({
              filePath: file,
              printerName: this.selectedPrinter,
              duplex: this.duplexPrinting,
              copies: this.copies
            })

            if (!result.success) {
              throw new Error(`打印失败: ${result.error || '未知错误'}`)
            }

            this.progress = ((i + 1) / this.files.length) * 100
            // 延时以防连续提交过快
            await new Promise(resolve => setTimeout(resolve, 1000))
          }

          this.showNotification(`成功打印 ${this.files.length} 个文件`, 'info')
          this.statusMessage = `打印完成 ${this.files.length} 个文件`
        } catch (error) {
          this.showNotification('打印出错: ' + error.message, 'error')
          this.statusMessage = '打印过程中出错'
        } finally {
          this.printingProgress = 0
        }
      },

      // 通知功能
      showNotification(message, type = 'info') {
        this.notification = { show: true, message, type }
        setTimeout(() => {
          this.notification.show = false
        }, 3000)
      }
    }
  }
  </script>

<style scoped>
/* 基础样式 */
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-image: url('@/assets/background.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  font-family: 'Comic Sans MS', 'Yuanti SC', 'Yuanti SC Regular', 'YouYuan', 'Microsoft YaHei', 'PingFang SC', sans-serif;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* 标题栏样式 */
.title-bar {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background: linear-gradient(to right, #FFF0F5, #FFE6F0);
  -webkit-app-region: drag;
  user-select: none;
  border-bottom: 1px solid rgba(255, 182, 193, 0.3);
}

.title-content {
  display: flex;
  align-items: center;
  -webkit-app-region: no-drag;
}

.title-icon {
  width: 32px;
  height: 32px;
  margin-right: 15px;
  filter: drop-shadow(0 2px 4px rgba(210, 54, 105, 0.2));
}

.title-text {
  color: #D23669;
  font-size: 18px;
  font-weight: bold;
  margin: 0;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

.title-buttons {
  display: flex;
  gap: 10px;
  -webkit-app-region: no-drag;
}

.title-button {
  width: 30px;
  height: 30px;
  border-radius: 15px;
  background: #FFB6C1;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title-button:hover {
  background: #FF9BB4;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.title-button.close:hover {
  background: #FF6B8B;
}

/* 主内容区样式 */
.main-content {
  display: flex;
  flex: 1;
  padding: 20px;
  gap: 20px;
  overflow: hidden;
}

.left-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: hidden;
}

.right-panel {
  width: 220px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 卡片样式 */
.printer-card, .search-card, .list-card {
  background: rgba(255, 255, 255, 0.85);
  border-radius: 15px;
  padding: 15px 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
}

.printer-card:hover, .search-card:hover, .list-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.printer-card {
  border: 2px dashed #FFB6C1;
  display: flex;
  align-items: center;
  gap: 15px;
}

.printer-icon {
  width: 32px;
  height: 32px;
  filter: drop-shadow(0 2px 4px rgba(210, 54, 105, 0.2));
}

.printer-select {
  flex: 1;
  border: 2px solid #FFB6C1;
  border-radius: 20px;
  padding: 10px 15px;
  background: #FFF0F5;
  color: #D23669;
  font-size: 14px;
  font-weight: bold;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23D23669' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 15px center;
  padding-right: 40px;
  box-shadow: 0 4px 8px rgba(255, 182, 193, 0.3);
  transition: all 0.3s ease;
}

.printer-select:hover {
  background-color: #FFE6F0;
  border-color: #FF9BB4;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(255, 182, 193, 0.4);
}

.printer-select:focus {
  outline: none;
  border-color: #FF9BB4;
  box-shadow: 0 0 0 3px rgba(255, 155, 180, 0.25), 0 4px 8px rgba(255, 182, 193, 0.3);
}

.refresh-button {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background: #F8D5E3;
  color: #D23669;
  border: 2px solid #FFB6C1;
  cursor: pointer;
  transition: all 0.2s ease;
}

.refresh-button:hover {
  background: #FFE5F1;
  transform: rotate(15deg);
}

.search-card {
  border: 2px dotted #FFD1DC;
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  flex: 1;
  border: 2px solid #FFD1DC;
  border-radius: 15px;
  padding: 10px 15px;
  background: white;
  color: #D23669;
  font-size: 14px;
  transition: all 0.2s ease;
}

.search-input:hover {
  border-color: #FFB6C1;
}

.search-input:focus {
  outline: none;
  border-color: #FF9BB4;
  box-shadow: 0 0 0 3px rgba(255, 155, 180, 0.25);
}

.clear-button {
  background: #FFD1DC;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 12px;
  color: #D23669;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.clear-button:hover {
  background: #FFB6C1;
  transform: scale(1.1);
}

.list-card {
  border: 2px dashed #FFB6C1;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.file-list-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background: rgba(255, 182, 193, 0.2);
  border-bottom: 1px solid #FFD1DC;
  font-weight: bold;
  color: #D23669;
}

.file-list-container {
  flex: 1;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #FFB6C1 #FFE5F1;
}

.file-list-container::-webkit-scrollbar {
  width: 8px;
}

.file-list-container::-webkit-scrollbar-track {
  background: #FFE5F1;
  border-radius: 4px;
}

.file-list-container::-webkit-scrollbar-thumb {
  background-color: #FFB6C1;
  border-radius: 4px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px dashed #FFE5F1;
  color: #D23669;
  cursor: pointer;
  transition: all 0.2s ease;
}

.file-item:hover {
  background: rgba(255, 240, 245, 0.7);
}

.file-item.selected {
  background: #FFD1DC;
  border-radius: 10px;
}

.file-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 70%;
}

.file-actions {
  display: flex;
  gap: 5px;
}

.file-actions button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  width: 30px;
  height: 30px;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.file-actions button:hover {
  background: rgba(255, 182, 193, 0.3);
  transform: scale(1.1);
}

/* 按钮样式 */
.action-button {
  background: #F8D5E3;
  color: #D23669;
  border: 2px solid #FFB6C1;
  border-radius: 20px;
  padding: 10px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.action-button:hover {
  background: #FFE5F1;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.action-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.spacer {
  flex: 1;
}

.print-button {
  background: linear-gradient(to right, #FF9A8B, #FF6B95);
  color: white;
  border: none;
  border-radius: 20px;
  padding: 12px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(255, 107, 149, 0.3);
}

.print-button:hover {
  background: linear-gradient(to right, #FF8A7B, #FF5B85);
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(255, 107, 149, 0.4);
}

.print-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 打印设置 */
.print-settings {
  background: rgba(255, 255, 255, 0.85);
  border-radius: 15px;
  padding: 15px;
  border: 2px dotted #FFD1DC;
  display: flex;
  flex-direction: column;
  gap: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.print-settings label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #D23669;
  font-size: 14px;
}

.print-settings input[type="checkbox"] {
  width: 18px;
  height: 18px;
  accent-color: #FF6B95;
}

.copies-input {
  width: 50px;
  border: 2px solid #FFD1DC;
  border-radius: 8px;
  padding: 5px;
  text-align: center;
  color: #D23669;
}

.copies-input:focus {
  outline: none;
  border-color: #FF9BB4;
}

/* 状态栏样式 */
.status-bar {
  height: 40px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-top: 2px solid #FFD1DC;
}

.status-info {
  color: #FF6B95;
  font-weight: bold;
  font-size: 13px;
  display: flex;
  gap: 15px;
}

.progress-container {
  flex: 1;
  height: 8px;
  border: 2px solid #FFD1DC;
  border-radius: 4px;
  background: white;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(to right, #FF9A8B, #FF6B95);
  border-radius: 4px;
  transition: width 0.3s ease;
}

/* 通知样式 */
.notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 15px 25px;
  background: rgba(255, 209, 220, 0.95);
  color: #D23669;
  border-radius: 15px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  animation: slideIn 0.3s ease;
  z-index: 1000;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 182, 193, 0.5);
  max-width: 300px;
}

.notification.error {
  background: rgba(255, 182, 193, 0.95);
  border-color: rgba(255, 107, 139, 0.5);
}

.notification-enter-active,
.notification-leave-active {
  transition: all 0.3s ease;
}

.notification-enter-from,
.notification-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

@keyframes slideIn {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>